﻿package main

import (
	"bufio"
	"bytes"
	"io"
	"log"
	"net"
	"net/http"
)

func runVhostServer(br *TcpBridgeHandler, addr string) {
	s, err := net.Listen("tcp4", addr)
	if err != nil {
		log.Println("listen error")
		return
	}

	for {
		c, err := s.Accept()
		if err != nil {
			log.Println("vhost s accept error!")
			break
		}
		// 解析host并缓存头部信息
		thConn := tcpHttpConn{
			TcpConn:      c,
			ClientTarget: "127.0.0.1:8080",
			Buffer:       bytes.NewBuffer(make([]byte, 0, 1024*2)),
			TcpBridge:    br,
		}
		go thConn.Run(io.TeeReader(c, thConn.Buffer))
	}
}

type tcpHttpConn struct {
	TcpConn      net.Conn
	ClientTarget string        // client 本地需要请求的地址，用于修改host
	Buffer       *bytes.Buffer // 缓存Header信息
	TcpBridge    *TcpBridgeHandler
}

func (t *tcpHttpConn) Run(rd io.Reader) {
	defer t.TcpConn.Close()
	// 解析http
	req, err := http.ReadRequest(bufio.NewReader(rd))
	if err != nil {
		log.Println("read http header from tcp conn error!")
		return
	}

	log.Println("tcpHttpConn run start", req.URL)

	// 更具oldHost转发到某个对应tcp
	node, ok := t.TcpBridge.ClientNodes[0]
	if ok {
		targetTcp, _ := node.TcpYamuxConn.Open()
		defer targetTcp.Close()

		// need change host?
		// 获取Host, 改写Header
		bBuff := t.Buffer.Bytes()
		// if len(t.ClientTarget) > 0 {
		// 	bBuff = bytes.Replace(bBuff, []byte(req.Host), []byte(t.ClientTarget), -1)
		// }
		log.Println(req.Host, req.URL.Path, "\r\n", string(bBuff))
		// copy header part
		targetTcp.Write(bBuff)
		// copy body and streams
		io.Copy(targetTcp, req.Body)
		t.Buffer.Reset()
		req.Body.Close()

		go io.Copy(t.TcpConn, targetTcp)

		// keep read for keep-alive connection
		io.Copy(targetTcp, t.TcpConn)

		log.Println("tcpHttpConn run over")
	}
}
